package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor{


    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    //实现登录拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{


         //排除跨域问题
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //1.判断当前请求方法上是否有@RequireLogin注解
        HandlerMethod hm = (HandlerMethod)handler;
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //2.如果有进行登录校验
        if(hm.hasMethodAnnotation(RequireLogin.class)){
            if(user == null){
                //没有登录
                response.setContentType("application/json;charset=utf-8");//json数据中文转码
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //3.如果没有直接放行
        return true;

        /*String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        if(user == null){
            //没有登录,返回没有登录的提示
            response.setContentType("application/json;charset=utf-8");//json数据中文转码
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }
        return true;
        */
    }
}
